package com.andy.blog.framework.security.handle;

import com.alibaba.fastjson2.JSON;
import com.andy.blog.common.constant.BaseConstants;
import com.andy.blog.common.core.domain.model.LoginUser;
import com.andy.blog.common.reponse.GeneralResponseResult;
import com.andy.blog.common.utils.ServletUtils;
import com.andy.blog.dal.vo.SysLoginLogVO;
import com.andy.blog.framework.manager.AsyncManager;
import com.andy.blog.framework.manager.factory.AsyncFactory;
import com.andy.blog.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 自定义退出处理类 返回成功
 * Created by andy on 2023-04-05 11:38
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Autowired
    private TokenService tokenService;

    /**
     * 退出处理
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (Objects.nonNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLoginLog(SysLoginLogVO.builder()
                    .userName(userName)
                    .status(BaseConstants.LOGOUT)
                    .clientType("")
                    .msg("退出成功")
                    .build()));
        }
        ServletUtils.renderString(response, JSON.toJSONString(GeneralResponseResult.success("退出成功")));
    }
}
